package com.scs.application.modules.fsd;

import com.jnrsmcu.sdk.netdevice.*;
import com.scs.application.modules.fsd.entity.FsdTemp;
import com.scs.application.modules.fsd.mapper.TempMapper;
import com.scs.application.modules.sys.utils.UtilDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//  ApplicationListener<ContextRefreshedEvent>
@Component
public class FsdStartService implements ApplicationRunner {
    private Logger log = LoggerFactory.getLogger("FsdStartService");
    //RSServer rsServer;
    //ExecutorService newSingleThreadPool;
    @Autowired
    private TempMapper tempMapper;

    String url;
    String driverClassName;
    String username;

     int RSServerPort;

    boolean RSServer_inactive;

    //@Autowired
    //JdbcTemplate jdbcTemplate;


    private DriverManagerDataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(UtilDatabase.getPassword(username));
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }


    @Override
    /**
     * 当程序启动完毕后执行，不影响程序启动速度 ApplicationArguments args
     */
     public void run(ApplicationArguments args) {
        log.info("FsdStartService:"+RSServer_inactive+RSServerPort);
        if(!RSServer_inactive) {
            ExecutorService newSingleThreadPool =  Executors.newSingleThreadExecutor();
            newSingleThreadPool.execute(() -> {
                try {
                    RSServer rsServer = getRSServer(RSServerPort);
                    rsServer.start();
                } catch (Exception e) {
                    log.error("FsdStartService:"+e.toString());
                }
            });
        }


    }

//    @Override
//    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)
//    {
//
//        CompletableFuture.supplyAsync(() -> {
//            try {
//                RSServer rsServer = getRSServer(RSServerPort);
//                log.info("FsdStartService:start");
//                rsServer.start();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            log.info("FsdStartService:end");
//            return "温湿度仪服务程序启动 ";
//        });
//    }

//        if(!RSServer_inactive) {
//            ExecutorService newSingleThreadPool =  Executors.newSingleThreadExecutor();
//            newSingleThreadPool.execute(() -> {
//                try {
//                    RSServer rsServer = getRSServer(RSServerPort);
//                    log.info("FsdStartService:start");
//                    rsServer.start();
//                    log.info("FsdStartService:end");
//                } catch (Exception e) {
//                    log.error("FsdStartService:"+e.toString());
//                }
//            });
//        }


//    @PreDestroy
//    private void destory() throws Exception{
//        rsServer.stop();
//        newSingleThreadPool.shutdown();
//        System.out.println("关闭server");
//    }
    /**
     * 温湿度服务
     * @return
     */
    public  RSServer getRSServer(int port)
    {
        RSServer rsServer = RSServer.Initiate(port);// 初始化
        rsServer.addDataListener(new IDataListener() {// 添加监听
            @Override
            public void receiveTimmingAck(TimmingAck data) {// 校时指令应答处理
              //  System.out.println("校时应答->设备编号:" + data.getDeviceId()+ "\t执行结果：" + data.getStatus());
                log.info("校时应答->设备编号:" + data.getDeviceId()+ "\t执行结果：" + data.getStatus());
            }

            @Override
            public void receiveTelecontrolAck(TelecontrolAck data) {// 遥控指令应答处理
                //System.out.println("遥控应答->设备编号:" + data.getDeviceId()  + "\t继电器编号:" + data.getRelayId() + "\t执行结果:" + data.getStatus());
                log.info("遥控应答->设备编号:" + data.getDeviceId()  + "\t继电器编号:" + data.getRelayId() + "\t执行结果:" + data.getStatus());
            }

            @Override
            public void receiveStoreData(StoreData data) {// 已存储数据接收处理
                // 遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中

//                DriverManagerDataSource dataSource = getDataSource();
//                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//                List stationlist=new ArrayList();
//                String station_code="";
//
//                for (NodeData nd : data.getNodeList()) {
//                    if(nd.getTem()==0||nd.getTem()==100||nd.getHum()==0)continue;
//                    try {
//                        //stationlist = jdbcTemplate.queryForList("select station_code from fsd_station where  humiture like '%"+data.getDeviceId()+"%'   limit 1",new Object[]{}, String.class);
//                        stationlist = jdbcTemplate.queryForList("select station_code From fsd_humiture where humiture_addr=? and humiture_no=?",new Object[]{data.getDeviceId(),nd.getNodeId()}, String.class);
//
//                    }catch (Exception ex)
//                    {
//                        log.info("StoreData:"+ex.toString());
//                    }
//                    if(stationlist.size()>0)
//                    {
//                        station_code=stationlist.get(0).toString();
//                    }else station_code="";
//
//                    SimpleDateFormat sdf = new SimpleDateFormat(
//                            "yy-MM-dd HH:mm:ss");
//                    String str = sdf.format(nd.getRecordTime());
//                    FsdTemp fsdTemp=new FsdTemp();
//                    fsdTemp.setAlert(0);//报警待实现
//                    //fsdTemp.setChestNo(Integer.valueOf(chest_no));
//                    fsdTemp.setChestNo(nd.getNodeId());
//                    fsdTemp.setDamp(nd.getHum()+"");
//                    fsdTemp.setTemp(nd.getTem()+"");
//                    fsdTemp.setStationCode(station_code);
//                    fsdTemp.setRecTime(nd.getRecordTime());
//                    fsdTemp.setGmtCreate(LocalDateTime.now());
//                    fsdTemp.setDeviceid(data.getDeviceId());
//                    fsdTemp.setDatatype("StoreData");
//                    tempMapper.insert(fsdTemp);
//                }

            }

            @Override
            public void receiveRealtimeData(RealTimeData data) {// 实时数据接收处理
                // 遍历节点数据。数据包括网络设备的数据以及各个节点数据。温湿度数据存放在节点数据中
                DriverManagerDataSource dataSource = getDataSource();
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
                List stationlist=new ArrayList();
                String station_code="";
                for (NodeData nd : data.getNodeList()) {
                    if(nd.getTem()==0||nd.getTem()==100||nd.getHum()==0)continue;
//                    System.out.println("实时数据->设备地址:" + data.getDeviceId()
//                            + "\t节点:" + nd.getNodeId() + "\t温度:" + nd.getTem()
//                            + "\t湿度:" + nd.getHum() + "\t经度:" + data.getLng()
//                            + "\t纬度:" + data.getLat() + "\t坐标类型:"
//                            + data.getCoordinateType() + "\t继电器状态:"
//                            + data.getRelayStatus());

                    try {
                        //stationlist = jdbcTemplate.queryForList("select station_code from fsd_station where  humiture like '%"+data.getDeviceId()+"%'   limit 1",new Object[]{}, String.class);
                        stationlist = jdbcTemplate.queryForList("select station_code From fsd_humiture where humiture_addr=? and humiture_no=?",new Object[]{data.getDeviceId(),nd.getNodeId()}, String.class);
                    }catch (Exception ex)
                    {
                        log.info("StoreData:"+ex.toString());
                    }
                    if(stationlist.size()>0)
                    {
                        station_code=stationlist.get(0).toString();
                    }else station_code="";

                    FsdTemp fsdTemp=new FsdTemp();
                    fsdTemp.setAlert(0);
                    //fsdTemp.setChestNo(Integer.valueOf(chest_no));
                    fsdTemp.setChestNo(nd.getNodeId());
                    fsdTemp.setDamp(nd.getHum()+"");
                    fsdTemp.setTemp(nd.getTem()+"");
                    fsdTemp.setStationCode(station_code);
                    fsdTemp.setRecTime(new Date());
                    fsdTemp.setGmtCreate(LocalDateTime.now());
                    fsdTemp.setDeviceid(data.getDeviceId());
                    fsdTemp.setDatatype("RealData");
                    tempMapper.insert(fsdTemp);
                }
            }

            @Override
            public void receiveLoginData(LoginData data) {// 登录数据接收处理
                //System.out.println("登录->设备地址:" + data.getDeviceId());
                log.info("登录->设备地址:" + data.getDeviceId());

            }

            @Override
            public void receiveParamIds(ParamIdsData data) {
                String str = "设备参数编号列表->设备编号：" + data.getDeviceId()
                        + "\t参数总数量：" + data.getTotalCount() + "\t本帧参数数量："
                        + data.getCount() + "\r\n";
                for (int paramId : data.getPararmIdList())// 遍历设备中参数id编号
                {
                    str += paramId + ",";
                }
                log.info(str);
               // System.out.println(str);
            }

            @Override
            public void receiveParam(ParamData data) {
                String str = "设备参数->设备编号：" + data.getDeviceId() + "\r\n";
                for (ParamItem pararm : data.getParameterList()) {
                    str += "参数编号："
                            + pararm.getParamId()
                            + "\t参数描述："
                            + pararm.getDescription()
                            + "\t参数值："
                            + (pararm.getValueDescription() == null ? pararm
                            .getValue() : pararm.getValueDescription()
                            .get(pararm.getValue())) + "\r\n";
                }
                //System.out.println(str);
                log.info(str);
            }

            @Override
            public void receiveWriteParamAck(WriteParamAck data) {
                String str = "下载设备参数->设备编号：" + data.getDeviceId() + "\t参数数量："
                        + data.getCount() + "\t"
                        + (data.isSuccess() ? "下载成功" : "下载失败");
                //System.out.println(str);
                log.info(str);
            }

            @Override
            public void receiveTransDataAck(TransDataAck data) {
                String str = "数据透传->设备编号：" + data.getDeviceId() + "\t响应结果："
                        + data.getData() + "\r\n字节数：" + data.getTransDataLen();
                //System.out.println(str);
                log.info(str);
            }
        });
        return  rsServer;
    }


}
